package com.wwc.bwcj.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.wwc.bwcj.R
import com.wwc.bwcj.activity.MainActivity
import com.wwc.bwcj.adapter.OrderAdapter
import com.wwc.bwcj.entity.OrderItem
import com.wwc.bwcj.util.OrderManager

/**
 *
 * 展示用户订单历史，显示用户的订单列表或无订单提示。
 */
class OrdersFragment : Fragment() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var noOrdersView: View
    private lateinit var goToOrderButton: Button
    private lateinit var orderAdapter: OrderAdapter
    private val orders = ArrayList<OrderItem>()

    // 加载布局
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_orders, container, false)
    }

    // 初始化UI组件和适配器
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recyclerView = view.findViewById(R.id.recycler_view)
        noOrdersView = view.findViewById(R.id.no_orders_layout)
        goToOrderButton = view.findViewById(R.id.btn_go_to_order)

        // 初始化适配器
        orderAdapter = OrderAdapter(orders)
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = orderAdapter

        // 设置去点单按钮点击事件
        goToOrderButton.setOnClickListener {
            // 跳转到点单页面
            val intent = Intent(context, MainActivity::class.java)
            startActivity(intent)
        }

        // 加载订单数据
        loadOrders()
    }

    // 订单数据加载
    private fun loadOrders() {
        orders.clear()
        orders.addAll(OrderManager.getOrders())

        if (orders.isEmpty()) {
            // 显示无订单提示
            noOrdersView.visibility = View.VISIBLE
            recyclerView.visibility = View.GONE
        } else {
            // 显示订单列表
            noOrdersView.visibility = View.GONE
            recyclerView.visibility = View.VISIBLE
            orderAdapter.notifyDataSetChanged()
        }
    }
}
